import 'dart:math';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../lib_baseview/lib_baseview.dart';
import '../../../interface/root_proxy_model.dart';
import '../model/room_music_center_controller.dart';
import '../page/room_music_page.dart';

class FloatMusicPlayingBar extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FloatMusicPlayingBarState();
  }
}

class _FloatMusicPlayingBarState extends State<FloatMusicPlayingBar>
    with TickerProviderStateMixin {
  RoomMusicCenterController? get centerController {
    try {
      RoomMusicCenterController controller =
          Get.find<RoomMusicCenterController>();
      _dispose = false;
      return controller;
    } catch (e) {}
    return null;
  }

  AnimationController? controller;
  Animation<double>? animation;
  bool _dispose = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _initAnim();
    });
  }

  void _initAnim() {
    controller =
        AnimationController(vsync: this, duration: const Duration(seconds: 10));
    animation = Tween<double>(begin: 0, end: 2 * pi).animate(controller!);
    controller!.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller!.reset();
        controller!.forward();
      }
    });
    controller!.addListener(() {
      if (mounted) setState(() {});
    });
    controller!.forward();
  }

  void _release() {
    controller?.clearListeners();
    controller?.clearStatusListeners();
    controller?.dispose();
    animation = null;
    controller = null;
  }

  @override
  void dispose() {
    _release();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (centerController == null ||
        centerController!.currentMusic == null ||
        _dispose) {
      _release();
      return const SizedBox.shrink();
    }
    if (controller == null) {
      _initAnim();
    }

    return FutureBuilder<MediaPlayerState>(
      future: centerController!.playState(centerController!.currentMusic),
      builder: (c, shot) {
        if (shot.hasData) {
          MediaPlayerState state = shot.data!;
          if (state == MediaPlayerState.playerStatePlaying) {
            return GestureDetector(
              onTap: () {
                RoomMusicPage.show();
              },
              child: Container(
                height: 42,
                decoration: const ShapeDecoration(
                    shape: StadiumBorder(), color: Color(0x14FFFFFF)),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(width: 8),
                    _posterImg,
                    const SizedBox(width: 5),
                    ConstrainedBox(
                      constraints: const BoxConstraints(maxWidth: 60),
                      child: GetBuilder<RoomMusicCenterController>(
                          builder: (logic) {
                        return Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(logic.currentMusic?.name ?? '',
                                maxLines: 1,
                                style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500)),
                            Text(logic.currentMusic?.singer ?? '',
                                maxLines: 1,
                                style: TextStyle(
                                    color: Colors.white.withOpacity(0.8),
                                    fontSize: 10)),
                          ],
                        );
                      }),
                    ),
                    const SizedBox(width: 8),
                    GetBuilder<RoomMusicCenterController>(builder: (logic) {
                      return GestureDetector(
                          onTap: () => logic.toggleMute(),
                          child: _buildIcon(
                            logic.mute
                                ? 'ic_room_music_bar_mute.svg'
                                : 'ic_room_music_bar_unmute.svg',
                          ));
                    }),
                    const SizedBox(width: 8),
                    GetBuilder<RoomMusicCenterController>(builder: (logic) {
                      if (logic
                          .isLocalMusicCode(logic.currentMusic?.songCode ?? 0))
                        return const SizedBox();
                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: GestureDetector(
                            onTap: () => logic.toggleLyric(),
                            child: _buildIcon(
                              'ic_room_music_bar_lyric.svg',
                            )),
                      );
                    }),
                    GetBuilder<RoomMusicCenterController>(builder: (logic) {
                      if (!logic.hasMultiTrack) return const SizedBox();
                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: GestureDetector(
                            onTap: () => logic.toggleAccompany(),
                            child: _buildIcon(
                              logic.accompany
                                  ? 'ic_room_music_bar_accompany.svg'
                                  : 'ic_room_music_bar_vocal.svg',
                            )),
                      );
                    }),
                    GestureDetector(
                        onTap: () {
                          RoomMusicPage.show();
                        },
                        child: _buildIcon('ic_room_music_bar_playlist.svg')),
                    const SizedBox(width: 8),
                    GestureDetector(
                        onTap: () {
                          Get.delete<RoomMusicCenterController>(force: true);
                          RootProxyModel.instance?.notifyListeners();
                          setState(() {
                            _dispose = true;
                          });
                        },
                        child: _buildIcon('ic_room_music_bar_close.svg')),
                    const SizedBox(width: 12),
                  ],
                ),
              ),
            );
          } else {
            return const SizedBox.shrink();
          }
        } else {
          return const SizedBox.shrink();
        }
      },
    );
  }

  _buildIcon(String iconName) =>
      image('packages/m_chatroom/assets/images/music/$iconName',
          wholePath: true, width: 24, height: 24);

  get _posterImg => Container(
        width: 32,
        height: 32,
        alignment: Alignment.center,
        decoration: const BoxDecoration(
            color: Color(0xFF010101), shape: BoxShape.circle),
        child: GetBuilder<RoomMusicCenterController>(builder: (logic) {
          if (logic.currentMusic == null) {
            return const SizedBox.shrink();
          }
          return ClipOval(
            child: Transform.rotate(
                angle: animation?.value ?? 0,
                child: image(logic.currentMusic!.poster ?? '',
                    width: 22, height: 22, fit: BoxFit.cover)),
          );
        }),
      );
}
